package net.udp.server;

   
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.text.SimpleDateFormat;

import net.udp.UDPProps;

import org.apache.log4j.Logger;

import core.Props;

public abstract class UDPServer implements Runnable{
	
	
	private Integer BUFFERSIZE;
	private Integer port;
	private  Props props;
	private  DatagramSocket sock;
	
	private static Logger log = Logger.getLogger(UDPServer.class);
	
//	private static UDPServer instance = null;
	
//  public static UDPServer getInstance()
//  {
//	  if(instance==null)
//		try {
//			instance=new UDPServer();
//		} catch (Exception e) {			
//			log.error(e.getLocalizedMessage());
//		    e.printStackTrace();
//		} 
//	  return instance;
//  }
//  
  
  
  public UDPServer() throws InstantiationException, IllegalAccessException, ClassNotFoundException
  {
	 
	  props = UDPProps.getInstance();	
	
	  port=props.getInt("server.port");
	  BUFFERSIZE=props.getInt("datagram.buffersize");	 
	   
//	  handler = (RequestHandler)(Class.forName(props.getString("server.requesthandler")).newInstance());
	  
	  
  }
  
  public void run()
  {
	  DatagramPacket pack = new DatagramPacket(new byte[BUFFERSIZE],  BUFFERSIZE);
	  String output = null;
	  try {
	    sock = new DatagramSocket(port);
	    log.debug("Server online!");
	  } catch (SocketException e) {
		  log.error(e.getLocalizedMessage());
	      e.printStackTrace();
	    return;
	  }
 
	  while (true) {
	    try {
	      sock.receive(pack);
	      log.debug(">>\t"+pack.getAddress()+"\t"+new String(pack.getData()));
	      output = process(new String(pack.getData()));
	      if(output!=null)
	      {
		      pack.setData(output.getBytes());		     
		      sock.send(pack);
	      }
	      log.debug("<<\t"+pack.getAddress()+"\t"+output);
	    } catch (IOException e) {
	    	log.error(e.getLocalizedMessage());
		    e.printStackTrace();
	    }
	    
	  }
  }
  
  
  
  
  abstract public String process(String string) throws IOException ;



//public static void main(String[] args) {
//	UDPServer.getInstance().run();
//  }
  
}

